package com.japancompany.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.japancompany.entity.File;
import com.japancompany.mapper.FileMapper;
import com.japancompany.service.FileService;
import com.japancompany.common.PageQuery;
import com.japancompany.common.PageResult;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements FileService {

    @Override
    public PageResult<File> getFilePage(PageQuery pageQuery, String fileName, String fileType) {
        Page<File> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        
        QueryWrapper<File> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        
        if (fileName != null && !fileName.trim().isEmpty()) {
            queryWrapper.like("file_name", fileName);
        }
        
        if (fileType != null && !fileType.trim().isEmpty()) {
            queryWrapper.eq("file_type", fileType);
        }
        
        queryWrapper.orderByDesc("create_time");
        
        Page<File> result = page(page, queryWrapper);
        
        return new PageResult<>(result.getTotal(), result.getRecords(), 
                (int) result.getCurrent(), (int) result.getSize());
    }

    @Override
    public boolean saveFile(String fileName, String filePath, String fileType, Long fileSize) {
        File file = new File();
        file.setFileName(fileName);
        file.setFilePath(filePath);
        file.setFileType(fileType);
        file.setFileSize(fileSize);
        file.setStatus(1);
        return save(file);
    }

    @Override
    public boolean deleteFile(Long id) {
        return removeById(id);
    }

    @Override
    public List<File> getFilesByType(String fileType) {
        return list(new QueryWrapper<File>()
                .eq("deleted", 0)
                .eq("file_type", fileType)
                .eq("status", 1)
                .orderByDesc("create_time"));
    }
}